package com.mz.ieann.aide.city.model

import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import com.mz.ieann.aide.base.vm.BaseViewModel
import com.mz.ieann.aide.city.bean.City
import com.mz.ieann.aide.city.bean.CityResult
import com.mz.ieann.dokit.utils.FileRead
import java.util.*
import kotlin.collections.ArrayList

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by Administrator
 * @date on 2021 2021/10/23 12:37
 */
class CityViewModel : BaseViewModel() {

    var letter : MutableLiveData<ArrayList<City>> = MutableLiveData()
    var result : MutableLiveData<ArrayList<City>> = MutableLiveData()

    /**
     * 获得字母列表
     */
    fun queryLetter(){
        request(
            query = {
                val letterList = ArrayList<City>()
                for (i in "A"[0].code.."Z"[0].code){
                    letterList.add(City((i.toChar()).toString(), ""))
                }
                letterList
            },
            catch = {
                it.add(0, City("#", ""))
                it
            },
            success = {
                letter.value = it
            }
        )
    }

    /**
     * 查询所有省下的城市保存在一个列表中
     */
    @RequiresApi(Build.VERSION_CODES.N)
    fun queryCity(context : Context){
        request(
            "city.txt",
            query = {
                FileRead.readAssets(context, CityResult::class.java, it)
            },
            catch = { result ->
                val resultList = result?.result
                val country = resultList?.get(0)
                val provinceList = country?.data
                val cityList = ArrayList<City>()
                cityList.add(City("北京", "#"))
                cityList.add(City("天津", "#"))
                cityList.add(City("上海", "#"))
                cityList.add(City("重庆", "#"))
                cityList.add(City("西安", "#"))
                cityList.add(City("杭州", "#"))
                provinceList?.let {
                    for (i in it.indices){
                        cityList.addAll(it[i].data!!)
                    }
                }
                Collections.sort(cityList, Comparator.comparingInt{ city ->
                    city.firstLetter[0].code
                })
                for (i in cityList.indices){
                    cityList[i].isFirst = (i - 1 < 0) || !cityList[i].firstLetter.equals(cityList[i - 1].firstLetter)
                }
                cityList
            },
            success = {
                result.value = it
            }
        )
    }

}